﻿using System;
using System.Net;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json.Linq;
using Top.Api;
using Top.Api.Util;
using TrinityAPI.Base;
using TrinityAPI.Base.Tools;
using TrinityAPI.Base.Models;
using System.Xml;
using Newtonsoft.Json;

namespace Taobao.Open.Platform
{
    /// <summary>
    /// 获取魅力惠订单收件人信息
    /// </summary>
    public class GetMeiOrderSensitiveInfo : IAction
    {
        public JToken Invoke(JObject dataset, params JToken[] args)
        {
            var request = dataset.GetJsonObject("request");
            var constant = dataset.GetJsonObject("constant");
            var taobaoMeiAPIConfig = constant.GetNecessaryJsonObject("taobaoMeiAPIConfig", "constant");

            string eShopCode = request.GetJsonObjectStringValue("eShopCode");
            string orderId = request.GetJsonObjectStringValue("orderId");

            if (string.IsNullOrWhiteSpace(eShopCode) || string.IsNullOrWhiteSpace(orderId))
                throw new Exception();

            var orderIds = orderId.Split('-');
            if (orderIds.Length == 2)
                orderId = orderIds[0];

            string url = taobaoMeiAPIConfig.GetNecessaryJsonObjectStringValue("url", "constant.taobaoMeiAPIConfig");
            string appkey = taobaoMeiAPIConfig.GetNecessaryJsonObjectStringValue("app_key", "constant.taobaoMeiAPIConfig");
            string appsecret = taobaoMeiAPIConfig.GetNecessaryJsonObjectStringValue("app_secret", "constant.taobaoMeiAPIConfig");
            string sellerId = taobaoMeiAPIConfig.GetNecessaryJsonObjectStringValue("seller_id", "constant.taobaoMeiAPIConfig");
            var proxy = taobaoMeiAPIConfig.GetJsonObjectValue("proxy");

            try
            {
                //var proxyHttpClientHandler = new HttpClientHandler();

                //if (proxy != null && proxy.Type == JTokenType.String && !string.IsNullOrWhiteSpace(proxy.ToString()) && proxy.ToString().IndexOf(":") > -1)
                //{
                //    string[] hostAndPort = proxy.ToString().Split(':');
                //    int port = 0;
                //    if (int.TryParse(hostAndPort[1], out port))
                //    {
                //        proxyHttpClientHandler.Proxy = new WebProxy(hostAndPort[0], port);
                //        proxyHttpClientHandler.UseProxy = true;
                //    }
                //}
                //else if (proxy != null && proxy.Type == JTokenType.Boolean && !proxy.Value<bool>())
                //{
                //    proxyHttpClientHandler.Proxy = null;
                //    proxyHttpClientHandler.UseProxy = false;
                //}

                var useProxy = proxy == null || proxy.Type != JTokenType.Boolean ? true : proxy.Value<bool>();
                var webUtils = new WebUtils() { DisableWebProxy = !useProxy };

                var getOrderParams = GetParams(appkey, appsecret, "tmall.luxury.vms.order.info.get", "main_biz_order_id", orderId);
                //string getOrderUrl = WebUtils.BuildRequestUrl(url, getOrderParams);
                string orderResponseString = webUtils.DoPost(url, getOrderParams);
                string oaid = JObject.Parse(orderResponseString).GetJsonObject("tmall_luxury_vms_order_info_get_response").GetJsonObject("result").GetJsonObject("value").GetJsonObjectStringValue("oaid");

                if (string.IsNullOrWhiteSpace(oaid))
                    throw new Exception(orderResponseString);

                var body = new JObject() {
                    { "seller_id", sellerId },
                    { "aid_list", new JArray() { new JObject() { { "order_id", orderId }, { "oaid", oaid } } } }
                };

                var getSensitiveInfoParams = GetParams(appkey, appsecret, "tmall.luxury.vms.aid.query", "param0", body.ToString(Newtonsoft.Json.Formatting.None));
                //string getSensitiveInfoUrl = WebUtils.BuildRequestUrl(url, getSensitiveInfoParams);
                string sensitiveInfoResponseString = webUtils.DoPost(url, getSensitiveInfoParams);
                JObject responseObject =  JObject.Parse(sensitiveInfoResponseString).GetJsonObject("tmall_luxury_vms_aid_query_response").GetJsonObject("result");

                if (responseObject == null)
                    throw new Exception(sensitiveInfoResponseString);

                if (responseObject.GetJsonObjectStringValue("success") != "true")
                    throw ExceptionHelper.GenException("@E110000002", responseObject.GetJsonObjectStringValue("error_msg"));
                JObject receiverInfo = null;
                var receiverList = responseObject.GetJsonObject("value").GetJsonObjectValue("receiver") as JArray;
                if (receiverList.Count == 1)
                    receiverInfo = receiverList[0] as JObject;

                var orderSensitiveInfo = new JObject();
                orderSensitiveInfo["orders_no"] = orderId;
                orderSensitiveInfo["receiver_name"] = receiverInfo.GetJsonObjectStringValue("name");
                orderSensitiveInfo["receiver_province"] = receiverInfo.GetJsonObjectStringValue("state");
                orderSensitiveInfo["receiver_city"] = receiverInfo.GetJsonObjectStringValue("city");
                orderSensitiveInfo["receiver_district"] = receiverInfo.GetJsonObjectStringValue("district");
                orderSensitiveInfo["receiver_address"] = receiverInfo.GetJsonObjectStringValue("address_detail");
                orderSensitiveInfo["receiver_telephone"] = ""; //receiverInfo.GetJsonObjectStringValue("mobile");
                orderSensitiveInfo["receiver_mobile"] = receiverInfo.GetJsonObjectStringValue("mobile");
                orderSensitiveInfo["oaid"] = receiverInfo.GetJsonObjectStringValue("oaid");
                return new JArray() { orderSensitiveInfo };
            }
            catch (BaseException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                    throw ex;
                throw new Exception(ex.Code);
            }
            catch (Exception ex)
            {
                LogHelper.Info("Taobao GetMeiOrderSensitiveInfo fail: " + ex.Message);
                throw new Exception("@E110000001");
            }
            
        }

        private TopDictionary GetParams(string apiKey, string apiSecret, string apiName, string bodyKey, string body)
        {
            TopDictionary txtParams = new TopDictionary();
            txtParams.Add(bodyKey, body);
            txtParams.Add(Constants.METHOD, apiName);
            txtParams.Add(Constants.VERSION, "2.0");
            txtParams.Add(Constants.SIGN_METHOD, Constants.SIGN_METHOD_HMAC);
            txtParams.Add(Constants.APP_KEY, apiKey);
            txtParams.Add(Constants.FORMAT, Constants.FORMAT_JSON);
            //txtParams.Add(Constants.PARTNER_ID, Constants.SDK_VERSION);
            txtParams.Add(Constants.TIMESTAMP, DateTime.Now);
            //txtParams.Add(Constants.TARGET_APP_KEY, request.GetTargetAppKey());
            //txtParams.Add(Constants.SESSION, session);
            //txtParams.AddAll(this.systemParameters);

            //if (this.useSimplifyJson)
            //{
            //    txtParams.Add(Constants.SIMPLIFY, "true");
            //}

            string sign = TopUtils.SignTopRequest(txtParams, apiSecret, Constants.SIGN_METHOD_HMAC);

            // 添加签名参数
            txtParams.Add(Constants.SIGN, sign);

            return txtParams;
        }
    }
}
